/**
 * ifuner 制作 @18658226071@163.com
 *
 * @format
 */

"use strict"

const utils = {
	objTostring(o) {
		return Object.prototype.toString.call(o).slice(8, -1)
	},
	isString(o) {
		//是否字符串
		return this.objTostring(o) === "String"
	},
	isNumber(o) {
		//是否数字
		return this.objTostring(o) === "Number"
	},
	isObj(o) {
		//是否对象
		return this.objTostring(o) === "Object"
	},
	isArray(o) {
		//是否数组
		return this.objTostring(o) === "Array"
	},
	isDate(o) {
		//是否时间
		return this.objTostring(o) === "Date"
	},
	isBoolean(o) {
		//是否boolean
		return this.objTostring(o) === "Boolean"
	},
	isFunction(o) {
		//是否函数
		return this.objTostring(o) === "Function"
	},
	isNull(o) {
		//是否为null
		return this.objTostring(o) === "Null"
	},
	isUndefined(o) {
		//是否undefined
		return this.objTostring(o) === "Undefined"
	},
	isFalse(o) {
		if (
			o == "" ||
			o == undefined ||
			o == null ||
			o == "null" ||
			o == "undefined" ||
			o == 0 ||
			o == false ||
			o == NaN
		)
			return true
		return false
	},
	isTrue(o) {
		return !this.isFalse(o)
	},
	importAll(r) {
		let __modules = []
		r.keys().forEach(key => {
			if (key !== "./index.js") {
				__modules.push(r(key).default)
			}
		})
		return __modules
	},
	formatBytes(bytes = 0) {
		if (bytes === 0) return "0 B"
		var k = 1024 // or 1024
		var sizes = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"]
		var i = Math.floor(Math.log(bytes) / Math.log(k))
		return (bytes / Math.pow(k, i)).toPrecision(3) + " " + sizes[i]
	},
	formatData(value, dataType) {
		if (utils.isObj(dataType)) {
			if (
				Object.prototype.hasOwnProperty.call(dataType, "default") &&
				(typeof value === "undefined" || value === null)
			) {
				value = dataType.default
			}
			if (Object.prototype.hasOwnProperty.call(dataType, "type") && typeof value !== dataType.type) {
				if (utils.isNumber(dataType)) {
					value = parseInt(value, 10)
				}
			}
		}
		return value
	},
	filterSearchParams(search = {}, SEARCH_KEYS) {
		if (!utils.isObj(search)) {
			console.error("search 参数必须是对象")
			return
		}
		const query = search || {}
		const params = {}
		for (const key in SEARCH_KEYS) {
			params[key] = utils.formatData(query[key], SEARCH_KEYS[key])
		}
		return params
	},
	getPercent(num = 0, total = 0) {
		num = parseFloat(num)
		total = parseFloat(total)
		if (isNaN(num) || isNaN(total)) {
			return "-"
		}
		console.log("total", total)
		console.log("num", num)
		return total <= 0 ? "0%" : Math.round((num / total) * 10000) / 100.0 + "%"
	},
	formatSearchParams(query = {}, SEARCH_KEYS = {}) {
		for (const key in query) {
			if (
				Object.prototype.hasOwnProperty.call(SEARCH_KEYS, key) &&
				Object.prototype.hasOwnProperty.call(SEARCH_KEYS[key], "default") &&
				utils.formatData(query[key], SEARCH_KEYS[key]) === SEARCH_KEYS[key].default
			) {
				delete query[key]
			}
		}
		return query
	}
}
export default utils
